package com.bmmtwabp.employeedashbord.task;

import com.bmmtwabp.employeedashbord.dao.HeatMapper;
import com.bmmtwabp.employeedashbord.domain.Heat;
import com.bmmtwabp.employeedashbord.service.HeatService;
import com.bmmtwabp.employeedashbord.util.*;
import java.util.Map;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @Description: 定时任务类
 * @Param:
 * @return:
 * @Author: fenghouzhi
 * @Date: 2018/9/5
 */
@Slf4j
@Component
public class ScheduledTasks {

  @Resource
  private HeatMapper heatMapper;

  @Resource
  private HeatService heatService;

  /**
   * 每到夜间十一点就将当天的热饭记录隐藏
   */
  @Scheduled(cron = "0 0 23 * * ?")
  public void hideHeatMethod() {
    String waitTime = DateUtil.getDate();
    heatMapper.hideHeatLists(waitTime);
    log.info("将今天的热饭记录设置为隐藏! ----   " + waitTime);
  }

  /**
   * 心跳信息发送
   */
  @Scheduled(cron = "0/10 * * * * ?")
  public void heart() {
    WebSocketUtil.sendMessageForAll("heart info:  " + System.currentTimeMillis());
    log.info("heart send success");
  }

  /**
   * 10秒轮训机制[11：30-13：00]，判断当前是否有用户阻塞热饭
   */
  @Scheduled(cron = "0/5 * * * * ?")
  //@Scheduled(cron = "0/10 30/1 11-14 * * ?")
  public void deferredHeat() {
    if (CodeUtil.WAIT_HEAT_MAP.size() > 0) {
      for (Map.Entry<String, Heat> entry : CodeUtil.WAIT_HEAT_MAP.entrySet()) {
        Heat heat = entry.getValue();
        log.info("heat info:  " + heat);
        heatService.findTimeOutMethod(heat.getZone());
        switch (heat.getHeatStatus()) {
          case 1:
            Integer heatWaitTimeLong = DateUtil.getTimeDifference(heat.getWaitTime());
            log.info("进入准备热饭的time info:   " + heatWaitTimeLong);
            if (heatWaitTimeLong != null && heatWaitTimeLong > CodeUtil.HEAT_WAIT_MAX_TIME) {
              heatService.overHeatByHeatId(heat.getId());
              String msg = "0," + heat.getOpenId() + ",有人准备热饭未开始导致排队阻塞，被移出队列!";
              WebSocketUtil.sendMessageForAll(msg);
            }
            break;
          case 2:
            log.info("{}-----正在有人热饭！", heat.getZone());
            WebSocketUtil.serverToClientMsg(null, heat.getZone() + "有人正在热饭");
            break;
          default:
            break;
        }
      }
    } else {
      log.info("当前无用户等待热饭------{}", CodeUtil.WAIT_HEAT_MAP.size());
    }
  }

}
